<style>
    .errorTxt{display: none;}
</style>

<div class="index confirmOrder">
  <div class="coMain">
    <div class="content-wrap">
      <h1 class="tt0">确认订单</h1>
      <div class="contactInfo">
        <h1 class="tt1">收货人信息</h1>
        <div class="box">
          <?php
            $default_address = $default_receiver = '';//初始化默认收货地址
          ?>
          <?php foreach( $all_address as $v ):?>
              <?php
                $v_province = \common\models\Region::region_list($v->province);
                $v_city = \common\models\Region::region_list($v->city);
                $v_district = \common\models\Region::region_list($v->district);

                //获取默认收货地址
                if( $v->is_default==1 ){
                    $default_address = $v_province.'&nbsp;'.$v_city.'&nbsp;'.$v_district.'&nbsp;'.$v->address_detail;
                    $default_receiver = $v->name.'&nbsp;&nbsp;&nbsp;'.$v->phone;
                }
              ?>
          <div class="oenInfo exitAddress <?=$v->is_default==1?'selected':''?>" data-address-id="<?=$v->id?>" onclick="changeAddress(this)">
            <p class="name"><?=$v->name?></p>
            <p class="phoneNumber"><?=$v->phone?></p>
            <p class="address">
                <span class="txt1">
                    <?=$v_province.'&nbsp;'.$v_city.'&nbsp;'.$v_district?>
                </span>
                <span class="detail"><?=$v->address_detail?></span>
            </p>
            <i class="fa fa-check currentIcon"></i>
            <span class="rewrite inlineBlock" value='<?=$v->id?>'>修改</span>
          </div>
          <?php endforeach;?>
          <div class="oenInfo newAddress">
            <i class="fa fa-plus addIcon"></i>
            <p class="addInfo">添加新地址</p>
          </div>

        </div>
      </div>

      <div class="distribution">
        <p class="bor"><span class="tt1">配送方式</span><span class="font14">添品网安排发货</span></p>
<!--        <p class="bor"><span class="tt1">发票</span><span class="invoice"><em class="check-box"></em>需要发票 <input type="text" class="input" placeholder="请填写发票抬头（选填）"><em class="txt3">如公司需要增值税发票，请拨打客服电话 400-888-8888</em></span></p>-->
        <div class="positionr msgBox"><span class="tt1 tt1Absolute">订单附言<em class="c-999">（选填）</em></span><span class="tt1 empty"></span>  <textarea name="" id="" cols="80" rows="1" placeholder="请输入留言内容（最多200字）" class="msg"></textarea></div>
      </div>

      <div class="shopList">
        <h1 class="tt1">购物车清单</h1>
<!--        <p class="noAllTips"><i class="fa fa-info-circle"></i>抱歉，您的货品暂时都不能购买，请<a href="">返回进货单</a>修改货品</p>-->
        <?php
            $total_num = 0;
            $total_price = 0;
        ?>
        <?php foreach( $shopping_carts as $v ):?>
            <?php
                $total_num += $v->product_num;
                $total_price += $v->product_price*$v->product_num;
            ?>
        <div class="list" data-id="<?=$v->id?>">
          <div class="info1">
            <a href="/product/<?=$v->product_id?>" style="color:#333">
              <p class="txt"><!-- <span class="ypIcon inlineBlock">样品</span> --> <?=$v->title?></p>
              <img src="<?=$v->img_url?>" alt="" class="img">
            </a>
          </div>
          <div class="weight"><?=$v->product_num?><?=$v->price_unit?></div>
          <div class="eval"><em>￥<?=$v->product_price?></em>×<em><?=$v->product_num?></em></div>
          <div class="onePrice">￥<?=$v->product_price*$v->product_num?></div>
        </div>
        <?php endforeach;?>

          <?php /*
        <div class="subInfo0">
          <p class="left txt0">重量合计：<?=$total_num?> kg    运费：￥23.00   运费说明 <span class="tip-icon">?</span></p>
          <div class="onePrice">￥<?=$total_price?></div>
          <div class="eval"><em class="number">7</em>件商品，总商品金额：</div>
        </div>

        <div class="subInfo1">
          <div class="onePrice">￥25.00</div>
          <div class="eval">运费：</div>
        </div>
            */?>
        <div class="subInfo2">
          <p class="left txt0"><a href="/mycount/cart-list" class="returnCart">＜返回购物车修改</a></p>
          <div class="totalPrice">￥<?=$total_price?></div>
          <div class="eval">应付总额：</div>
        </div>

      </div>

      <div class="payInfo">
        <a href="javascript:;" class="btn-middle-default payBtn">立即支付</a>
        <p class="txt1">寄送至：<span class="address"><?=$default_address?></span></p>
        <p class="txt2">收货人：<span class="name"><?=$default_receiver?></span></p>
      </div>



    </div>
  </div>

  <div class="mask"></div>
  <div class="formPop">
    <p>管理收获地址
      <img src="http://static.tianpinwang.com.cn/v1/images/closeIcon1.png" alt="" class="closeForm">
    </p>
    <form id="form_address">
      <div class="item">
        <span class="txt0">收获姓名
          <img src="http://static.tianpinwang.com.cn/v1/images/star.png" alt="" class="star">
        </span>
        <input type="text" name="name">
        <p class="errorTxt">请输入正确的中文姓名</p>
      </div>
      <div class="item">
        <span class="txt0">省份
          <img src="http://static.tianpinwang.com.cn/v1/images/star.png" alt="" class="star">
        </span>
        <select name="province" id="province">
          <option value="">省份</option>
           <?php
           foreach ($region as $k => $v) {
               echo '<option value="'.$v['id'].'">'.$v['name'].'</option>';
           }
           ?>
        </select>
        <select name="city" id="city">
          <option value="">城市</option>
        </select>
        <select name="district" id="district">
          <option value="">区县</option>
        </select>
        <p class="errorTxt">请选择省份区域</p>
      </div>
      <div class="item">
        <span class="txt0">详细地址
          <img src="http://static.tianpinwang.com.cn/v1/images/star.png" alt="" class="star">
        </span>
        <input type="text" name="address_detail">
        <p class="errorTxt">请输入正确的收获地址</p>
      </div>
      <div class="item">
        <span class="txt0">手机号码
          <img src="http://static.tianpinwang.com.cn/v1/images/star.png" alt="" class="star">
        </span>
        <input type="number" name="phone" onkeyup="this.value=this.value.replace(/\D/g,'')" maxlength="11">
        <p class="errorTxt">请输入11位手机号码</p>
      </div>
      <div class="item">
        <span class="txt0">固定电话</span>
        <input type="text" name="tel" onkeyup="this.value=this.value.replace(/\D/g,'')">
      </div>
      <div class="item">
        <span class="txt0">邮政编码</span>
        <input type="number" name="zip_code"onkeyup="this.value=this.value.replace(/\D/g,'')" maxlength="6">
      </div>
      <div class="item">
        <span class="txt0"></span>
        <span class="btn-small-default confirmForm" id="add_address">确认</span>
        <span class="btn-small-empty cancelForm">取消</span>
      </div>
    </form>
  </div>

</div>

<script>
$(function(){
    var $formForm=$('.formPop')
    var $mask=$('.mask');
    $('.newAddress').click(function(){
      $formForm.css('display','block');
      $mask.css('display','block');
        $('#add_address').attr('value',1);
        $("input[name='name']").val("");
        $("input[name='address_detail']").val("");
        $("input[name='phone']").val("");
        $("input[name='tel']").val("");
        $("input[name='zip_code']").val("");

        $('#district').html('<option>请选择</option>');
        $('#city').html('<option>请选择</option>');
        var select = document.getElementById("province");  
        for(var i=0; i<select.options.length; i++){  
          if(select.options[i].innerHTML == "省份"){  
            select.options[i].selected = true;
            break;
          }
        }
    });
    $('.cancelForm,.closeForm').click(function(){
      $formForm.css('display','none');
      $mask.css('display','none');
    });


    $('.rewrite').on('click',function(){
      $formForm.css('display','block');
      $mask.css('display','block');
      $('#add_address').attr('value',0);
      $('#add_address').attr('name',$(this).attr('value'));

      //获取当前地址的信息
      var id = $(this).attr('value');
      var _csrf = <?php echo '"'.Yii::$app->request->getCsrfToken().'"'?>;
      $.post('',{'add_id':id,'_csrf':_csrf},function(data){
        var data = eval('('+data+')');
        $("input[name='name']").val(data['name']);
        $("input[name='address_detail']").val(data['address_detail']);
        $("input[name='phone']").val(data['phone']);
        $("input[name='tel']").val(data['tel']);
        $("input[name='zip_code']").val(data['zip_code']);

        var select = document.getElementById("province");  
        for(var i=0; i<select.options.length; i++){  
          if(select.options[i].getAttribute('value') == data['province']){  
            select.options[i].selected = true;
            break;
          }
        }
        var city_list = data['city_list'];
        var dis_list = data['dis_list'];
        var city = '';
        var town = '';
        
        for(var k in city_list){
          city += '<option value="'+city_list[k]["id"]+'">'+city_list[k]["name"]+'</option>';
        }
        for (var j in dis_list) {
          town += '<option value="'+dis_list[j]['id']+'">'+dis_list[j]["name"]+'</option>';
        }

        $('#city').html('');
        $('#district').html('');
        $('#district').html(town);
        $('#city').html(city);

        var select = document.getElementById("city");  
        for(var i=0; i<select.options.length; i++){  
          if(select.options[i].getAttribute('value') == data['city']){  
            select.options[i].selected = true;
            break;
          }
        }
        var select = document.getElementById("district");  
        for(var i=0; i<select.options.length; i++){  
          if(select.options[i].getAttribute('value') == data['district']){  
            select.options[i].selected = true;
            break;
          }
        }

      });
    });

    var $contactInfo=$('.contactInfo');
    $contactInfo.find('.exitAddress').on('click',function(){
      $(this).addClass('selected').siblings('.exitAddress').removeClass('selected');
    });

//    //需要开发票
//    $('.invoice').find('.check-box').on('click',function(){
//      if(!$(this).hasClass('selected')){
//          $(this).addClass('selected');
//          $(this).siblings('.input').show();
//      }else {
//          $(this).removeClass('selected');
//          $(this).siblings('.input').hide();
//      }
//    });


    

    //城市联动
    var city_json = <?= $cityJson;?>;
    $('select[name=province]').change(function () {
        var id = $(this).val();
        $.each(city_json, function (i, item) {
            if (item.id == id) {
                var str = '<option value="">城市</option>';
                $.each(item.child, function (j, jtem) {
                    str += '<option value="'+jtem.id+'">'+jtem.name+'</option>';
                });
                $('select[name=city]').html(str);
            }
        });
        $('select[name=district]').html('<option value="">区县</option>');
    });
    $('select[name=city]').change(function () {
        var pro_id = $("#province option:selected").val();
        var id = $(this).val();
        $.each(city_json, function (i, item) {
            if (item.id == pro_id) {

                $.each(item.child, function(c, cnima){
                    if( cnima.id==id ){
                        var str = '<option value="">区县</option>';
                        $.each(cnima.district, function (j, jtem) {
                            str += '<option value="'+jtem.id+'">'+jtem.name+'</option>';
                        });
                        $('select[name=district]').html(str);
                    }
                });
            }
        });
    });

    //添加新地址
    $('#add_address').click(function(){
        var $name = $("input[name='name']"),
            $province = $('#province option:selected'),
            $city = $('#city option:selected'),
            $district = $('#district option:selected'),
            $address_detail = $("input[name='address_detail']"),
            $phone = $("input[name='phone']"),
            $tel = $("input[name='tel']"),
            $zip_code = $("input[name='zip_code']"),
            data = $('#form_address').serialize();
        if($(this).attr('value') == 0){ //修改
          var save_update = new Array();
          save_update[0] = $(this).attr('value');    //为1是添加---为0是修改
          save_update[1] = $("input[name='name']").val();
          save_update[2] = $("input[name='phone']").val();
          save_update[3] = $("input[name='tel']").val();
          save_update[4] = $("input[name='zip_code']").val();
          save_update[5] = $("input[name='address_detail']").val();
          save_update[6] = $('#province').val();
          save_update[7] = $('#city').val();
          save_update[8] = $('#district').val();
          save_update[9] = $(this).attr('name');


          if(!save_update[1] || !save_update[2] || save_update[2].length!=11 || !save_update[5] || !save_update[6] || !save_update[7] || !save_update[8] || !save_update[9]){
            layer.msg('数据有误，请核对！', {time: 1000});
            return false;
          }
          var list = JSON.stringify(save_update);
          $.ajax({
            url: '/address/update',
            type: 'POST',
            dataType: 'text',
            data:{ 'save_update':list,"_csrf":<?php echo '"'.Yii::$app->request->getCsrfToken().'"'?>},
            success: function(data){
              if(data>0){

                $formForm.css('display','none');
                $mask.css('display','none');
                layer.msg('收货地址修改成功', {time: 1000}, function(){
                  window.location.href = "";
                });
              }else{
                layer.msg('数据有误，请完善后重试', {time: 1000}, function(){
                  //window.location.href = "";
                });
              }
                  
            },
            error: function(){
                layer.msg('数据错误，请稍后重试', {time: 1000}, function(){
                  window.location.href = "";
                });
            }
          });

        }else{
          if( !$name.val() ){
            $name.addClass('errorBor');
            $name.next('p:first').show();
            return false;
          }else{
              $name.removeClass('errorBor');
              $name.next('p:first').hide();
          }

          if( !$province.val() ){
              $province.parent().siblings('.errorTxt').show();
              return false;
          }else{
              $province.parent().siblings('.errorTxt').hide();
          }

          if( !$city.val() ){
              $city.parent().siblings('.errorTxt').show();
              return false;
          }else{
              $city.parent().siblings('.errorTxt').hide();
          }

          if( !$district.val() ){
              $district.parent().siblings('.errorTxt').show();
              return false;
          }else{
              $district.parent().siblings('.errorTxt').hide();
          }

          if( !$address_detail.val() ){
              $address_detail.addClass('errorBor');
              $address_detail.next('p:first').show();
              return false;
          }else{
              $address_detail.removeClass('errorBor');
              $address_detail.next('p:first').hide();
          }

          if( !$phone.val() ){
              $phone.addClass('errorBor');
              $phone.next('p:first').show();
              return false;
          }else{
              $phone.removeClass('errorBor');
              $phone.next('p:first').hide();
          }

          $.ajax({
              type: "POST",
              url: "/address/add",
              data: data+"&_csrf=<?=Yii::$app->request->getCsrfToken()?>",
              dataType: "json",
              success: function(data){
                  if(!data.errNo){
                      layer.msg(data.msg,{time:2000});
                      window.location.reload();
                  }else{
                      layer.msg(data.msg,{time:2000});
                  }
              }
          });
        }
    });

    //提交支付
    $('.payInfo .payBtn').click(function(){
        var address_id = $('.contactInfo .box .selected').attr('data-address-id'),
            message = $('.msgBox .msg').val(),
            ids = '';
        $('.shopList .list').each(function(e, item){
            ids += '-'+$(item).attr('data-id');
        });
        if( address_id==undefined ){
            layer.msg('请添加收货地址',{time:2000});
            return false;
        }
        $.ajax({
            type: "POST",
            url: "/order/confirm",
            data: "ids="+ids+"&address_id="+address_id+"&message="+message+"&_csrf=<?=Yii::$app->request->getCsrfToken()?>",
            dataType: "json",
            success: function(data){
                if(!data.errNo){
                    window.location=data.url;
                }else{
                    layer.msg(data.msg,{time:2000});
                }
            }
        });

    });

});

//更换收货地址
function changeAddress(_this){
    var address = $(_this).find('.address .txt1').text()+'  '+$(_this).find('.address .detail').text(),
        receiver = $(_this).find('.name').text()+'   '+$(_this).find('.phoneNumber').text();

    $('.payInfo .txt1 .address').text(address);
    $('.payInfo .txt2 .name').text(receiver);

}
</script>